<template>
  <div class="content">
    <el-button type="primary" @click="handleAddMenu">+ 添加菜单</el-button>
    <!-- 菜单抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="30%" direction="rtl">
      <el-form class="form-inline" :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio :value="0">目录</el-radio>
            <el-radio :value="1">菜单</el-radio>
            <el-radio :value="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="formData.icon" placeholder="请输入图标" clearable></el-input>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="formData.path" placeholder="请输入路径" clearable></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="formData.state">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="form-button">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 菜单表格 -->
    <el-table :data="dataList" style="width: 100%;margin-top: 20px;" row-key="id"
      :tree-props="{ children: 'children' }">
      <el-table-column prop="name" label="菜单名称" min-width="150"></el-table-column>
      <el-table-column prop="type" label="菜单类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getMenuTypeTag(row.type)">
            {{ getMenuTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="80"></el-table-column>
      <el-table-column prop="componentPath" label="组件路径" min-width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="icon" label="图标" min-width="150">
        <template #default="{ row }">
          <el-icon v-if="row.icon">{{ parsedIcon(row.icon) }}</el-icon>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="isCache" label="页面缓存" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isCache === 0 ? 'info' : 'success'">
            {{ row.isCache === 0 ? '不缓存' : '缓存' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isDisplay" label="是否显示" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isDisplay === 0 ? 'success' : 'info'">
            {{ row.isDisplay === 0 ? '显示' : '不显示' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="linkType" label="跳转类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.linkType === 0 ? '' : 'warning'">
            {{ row.linkType === 0 ? '系统' : '外链' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="路径" min-width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="powerName" label="权限标识" min-width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="state" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.state === 0 ? 'success' : 'danger'">
            {{ row.state === 0 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getTreeMenuAPI, addMenuAPI, updateMenuAPI, deleteMenuAPI } from '@/api/menu'
import type { MenuItem } from '@/types'


// 菜单抽屉
const drawerVisible = ref(false)
const drawerTitle = ref('添加菜单')
const isEdit = ref(false)

const formRef = ref<FormInstance>()
const formData = reactive<MenuItem>({
  name: '',
  type: 0,
  icon: '',
  path: '',
  sort: 0,
  state: 0,
})
// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 解析图标字段（提取纯图标名称）
const parsedIcon = (iconStr: string) => {
  return iconStr.split(' ')[0];
};

// 表单数据
const dataList = ref<MenuItem[]>([])

// 获取菜单类型文本
const getMenuTypeText = (type: number) => {
  const typeMap: { [key: number]: string } = {
    0: '目录',
    1: '菜单',
    2: '按钮'
  }
  return typeMap[type] || '未知'
}

// 获取菜单类型标签样式
const getMenuTypeTag = (type: number) => {
  const typeMap: { [key: number]: string } = {
    0: '',
    1: 'success',
    2: 'warning'
  }
  return typeMap[type] || 'info'
}
// 添加菜单
const handleAddMenu = () => {
  console.log("添加菜单按钮被点击");
  drawerTitle.value = '添加菜单'
  isEdit.value = false
  handleReset()
  drawerVisible.value = true
  console.log(drawerVisible.value)
}
// 编辑菜单
const handleEdit = (row: MenuItem) => {
  drawerTitle.value = '编辑菜单'
  isEdit.value = true
  Object.assign(formData, { ...row })
  drawerVisible.value = true
}
// 删除菜单
const handleDelete = async (row: MenuItem) => {
  try {
    await ElMessageBox.confirm('确定删除该菜单吗？', '提示', {
      type: 'warning'
    })
    await deleteMenuAPI(row.id!)
    ElMessage.success('删除成功')
    loadMenuList()
  } catch (error) {
    console.log("删除取消或出错:", error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  try {
    if (isEdit.value) {
      await updateMenuAPI(formData)
      ElMessage.success('修改成功')
    } else {
      await addMenuAPI(formData)
      ElMessage.success('添加成功')
    }

    drawerVisible.value = false
    loadMenuList()
  } catch (error) {
    ElMessage.error('操作失败')
    console.log(error)
  }
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    name: '',
    type: 0,
    icon: '',
    path: '',
    componentPath: '',
    powerName: '',
    sort: 0,
    state: 0,
    isCache: 0,
    isDisplay: 0,
    linkType: 0
  })
}

// 加载菜单列表 - 改为获取所有数据
const loadMenuList = async () => {
  try {
    const response = await getTreeMenuAPI()  // 使用树形菜单接口获取所有数据

    // 根据实际响应结构调整
    if (response.code === 200) {
      dataList.value = response.result || []
    } else {
      ElMessage.error(response.message || '加载失败')
    }
  } catch (error) {
    console.error('加载菜单列表失败:', error)
    ElMessage.error('加载菜单列表失败')
  }
}

// 初始化
onMounted(() => {
  loadMenuList()
})

</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
  font-size: 14px;
  background-color: #ffffff;
  padding: 20px;
}

.el-drawer {
  z-index: 999;
}

:deep(.el-table) {
  border: 1px solid #ebeef5;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #101010;
  font-weight: 600;
  text-align: center;
}

:deep(.el-table td) {
  padding: 12px 0;
  text-align: center;
}

:deep(.el-button) {
  margin-right: 8px;
}
</style>
